﻿using Books.Adapters;
using Books.Models;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Books.Controllers
{
    public class HomeController : Controller
    {
        private IBookAdapter _adapter;

        public HomeController()
        {
            _adapter = new BookDataAdapter();
        }
        public HomeController(IBookAdapter adapter)
        {
            _adapter = adapter;
        }
        public ActionResult Index()
        {
            string userId = User.Identity.GetUserId();

            BookListViewModels model = new BookListViewModels();
            //using the using state it will auto delete this from garbage
            // This also creates a transaction or unit of work

            //MovieDataAdapter adapter = new MovieDataAdapter(); This is commented out because we created the private class above. And instatiated it in the HomeController

            model.Books = _adapter.GetBooks(userId);

            model.UserName = User.Identity.GetUserName();
            model.AverageRating = model.Books.Average(m => m.Rating);

            return View(model);
        }
        public ActionResult Create()
        {
            BookViewModel model = new BookViewModel();


            return View(model);
        }
        [HttpPost]
        // We pass in the MovieViewModel because that is what they gave to us.
        public ActionResult Create(BookViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            string userId = User.Identity.GetUserId();



            _adapter.CreateBook(model, userId);

            return RedirectToAction("Index");
        }
    }
}
